/*
 * @lc app=leetcode.cn id=445 lang=typescript
 *
 * [445] 两数相加 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

//  思路：迭代、栈
//  将数据存于栈中,再计算出结果存与节点中，注意进位和数据的存储方向

//  复杂度：O(n) O(n)

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    const stack1 = [], stack2 = []
    while (l1) {
        stack1.push(l1.val)
        l1 = l1.next
    }
    while (l2) {
        stack2.push(l2.val)
        l2 = l2.next
    }

    let carry = 0
    let newHead = null
    while (stack1.length || stack2.length || carry) {
        const v1: number = stack1.pop() ?? 0
        const v2: number = stack2.pop() ?? 0
        const value = v1 + v2 + carry
        const nodeVal = value % 10
        carry = value < 10 ? 0 : 1
        const curr = new ListNode(nodeVal)
        curr.next = newHead
        newHead = curr
    }
    return newHead
};
// @lc code=end
import { ListNode } from "./type"
const l1 = new ListNode(9)
const l2 = new ListNode(5)
console.log(ListNode.printList(addTwoNumbers(l1, l2)))
